/*
 * Copyright 2016-2036 the original author or authors.
 * 
 * COMMERCIAL USE OF THIS SOFTWARE WITHOUT WARRANTY IS NOT ALLOWED.
 * Use is subject to license terms! You can distribute a copy of this software
 * to others for free. This software is a non-profit and open-source project.
 * Any contribution to this project will make it better.
 * All rights reserved! Owned by Stephen Liu.
 * 
 */
package com.github.arrow.function.v6;

import com.github.arrow.function.Callback;

import java.util.function.Function;

/**
 * @author ste7en.liu@gmail.com
 * @since 2016/10/18
 */
public interface AsynJob<T> {

    void start(Callback<T> callback);

    default <R> AsynJob<R> map(final Function<T, AsynJob<R>> function) {
        final AsynJob<T> source = this;
        return callback ->
            source.start(new Callback<T>() {
                @Override
                public void onResult(T t) {
                    function.apply(t)
                        .start(new Callback<R>() {
                            @Override
                            public void onResult(R r) {
                                callback.onResult(r);
                            }

                            @Override
                            public void onError() {
                                callback.onError();
                            }
                        });
                }

                @Override
                public void onError() {
                    callback.onError();
                }
            });

    }
}
